import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import StudentTaskCenter from '../views/StudentTaskCenter.vue'
import TeacherCenter from '../views/TeacherCenter.vue'
import LoginView from '../views/LoginView.vue'
import { isLoggedIn, getAuth } from '../utils/auth'
import DoTaskView from '../views/DoTaskView.vue'
import Demo from '../views/Demo.vue'

export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/student-tasks',
      name: 'student-tasks',
      component: StudentTaskCenter
    },
    {
      path: '/task/:id',
      name: 'do-task',
      component: DoTaskView
    },
    {
      path: '/teacher',
      name: 'teacher',
      component: TeacherCenter
    },
    {
      path: '/demo/:id',
      name: 'demo',
      component: Demo
    }
  ]
})

// 路由守卫：未登录访问中心页跳转到登录
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const protectedPaths = ['/student-tasks', '/teacher']
  if (protectedPaths.includes(to.path)) {
    if (!isLoggedIn()) return next({ path: '/login', query: { redirect: to.fullPath } })
  }
  // 已登录但无角色时也跳转登录
  const auth = getAuth()
  if (protectedPaths.includes(to.path) && !auth?.role) {
    return next({ path: '/login', query: { redirect: to.fullPath } })
  }
  next()
})